<template>
  <div>
    <el-collapse-transition>
      <card-search v-if="searchCardShow">
        <el-form ref="form" :model="form" label-width="80px" :inline="true">
          <el-form-item label="菜单状态">
            <el-select
              v-model="value"
              placeholder="请选择"
              style="width: 250px"
              clearable
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              class="btn-search"
              round
              icon="el-icon-search"
              size="medium"
              @click="initTable"
              >搜索</el-button
            >
            <el-button
              class="btn-search"
              round
              icon="el-icon-refresh"
              size="medium"
              @click="resetForm"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </card-search>
    </el-collapse-transition>

    <card-table style="height: calc(100vh - 100px)">
      <div class="card-table-header">
        <div class="card-table-header-btns">
          <el-button
            v-if="isSuperAdmin || hasPermission('system:menu:add')"
            class="btn-search"
            size="small"
            icon="el-icon-plus"
            @click="handleClick(null, 'add')"
            >新增</el-button
          >
          <!-- <el-button
            type="success"
            size="small"
            icon="el-icon-edit"
            @click="handleClick(null, 'edit')"
            >修改</el-button
          > -->
          <el-button class="btn-search" size="small" @click="toggleExpandAll">
            <svg-icon icon-class="collaspe" />展开/折叠</el-button
          >
          <el-input
            v-if="isSuperAdmin || hasPermission('system:menu:list')"
            placeholder="请输入菜单名称"
            style="width: 450px; margin-left: 10px"
            clearable
            size="small"
            v-model="input"
            @change="initTable"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="initTable"
            ></el-button>
          </el-input>
        </div>
        <div class="card-table-header-actions">
          <table-action
            :table-header="tableHeader"
            :search-show="hasPermission('system:menu:list') || isSuperAdmin"
            @check-change="handleCheckChange"
            @search-click="handleSearchClick"
            @init-click="handleInitClick"
          />
        </div>
      </div>

      <el-table
        :key="tableKey"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :header-cell-style="{ background: '#eff3f8', color: '#333' }"
        border
        stripe
        row-key="menuId"
        :default-expand-all="false"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
          indent: 20,
        }"
        :max-height="tableHeight"
        size="small"
      >
        <el-table-column
          v-for="item in tableHeader"
          v-if="item.visible"
          :key="item.prop"
          :label="item.title"
          :min-width="item.width"
          :prop="item.prop"
          :align="item.align"
        >
          <template v-if="item.prop === 'menuName'" #default="scope">
            <svg-icon
              v-if="scope.row.icon && scope.row.icon != '#'"
              :icon-class="scope.row.icon"
              style="margin-right: 5px; width: 16px; height: 16px"
            />

            <span style="margin-left: 5px">{{ scope.row[item.prop] }}</span>
          </template>
          <template v-else-if="item.prop === 'visible'" #default="scope">
            <span style="color: '#1AB394'" v-if="scope.row[item.prop] == 0"
              >显示</span
            >
            <span style="color: '#ED5565'" v-else>隐藏</span>
          </template>
          <template v-else-if="item.prop === 'menuType'" #default="scope">
            <span style="margin-left: 5px" v-if="scope.row[item.prop] == 'M'"
              >目录</span
            >
            <span style="margin-left: 5px" v-if="scope.row[item.prop] == 'C'"
              >菜单</span
            >
            <span style="margin-left: 5px" v-if="scope.row[item.prop] == 'F'"
              >按钮</span
            >
          </template>
          <template v-else #default="scope">
            {{ scope.row[item.prop] }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="280" align="center" v-if="isSuperAdmin || hasPermission('system:menu:edit') || hasPermission('system:menu:add') || hasPermission('system:menu:remove')">
          <template slot-scope="scope">
            <el-button
              v-if="isSuperAdmin || hasPermission('system:menu:edit')"
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleClick(scope.row, 'edit')"
              >编辑</el-button
            >
            <el-button
              v-if="isSuperAdmin || hasPermission('system:menu:add')"
              type="primary"
              size="mini"
              icon="el-icon-plus"
              @click="handleClick(scope.row, 'add')"
              >新增</el-button
            >
            <el-button
              v-if="isSuperAdmin || hasPermission('system:menu:remove')"
              type="primary"
              size="mini"
              icon="el-icon-delete"
              @click="handleClick(scope.row, 'delete')"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </card-table>
    <dialog-menu
      v-model="dialogMenuVisible"
      :field="field"
      :menuRow="menuRow"
      @success="initTable"
      @close="
        () => {
          dialogMenuVisible = false;
        }
      "
    />
  </div>
</template>
<script>
import CardSearch from "@/components/CardSearch";
import CardTable from "@/components/CardTable";
import TableAction from "@/components/TableAction";
import DialogMenu from "./component/DialogMenu.vue";
import { menuList, menuDelete } from "@/api/systemmanagement";
import { hasPermission, isSuperAdmin } from "@/utils/hasBtnPermission";
export default {
  name: "BusinessList",
  components: {
    CardSearch,
    CardTable,
    TableAction,
    DialogMenu,
  },
  data() {
    return {
      tableKey: 0, // 用于强制刷新表格
      searchCardShow: false,
      input: "",
      value: "2",
      tableHeight: 550,
      form: {},
      options: [
        {
          value: "2",
          label: "所有",
        },
        {
          value: "0",
          label: "显示",
        },
        {
          value: "1",
          label: "隐藏",
        },
      ],

      tableHeader: [
        {
          title: "菜单名称",
          prop: "menuName",
          width: "150",
          visible: true,
          align: "left",
        },
        {
          title: "排序",
          prop: "orderNum",
          width: "100",
          visible: true,
          align: "center",
        },
        {
          title: "页面路径",
          prop: "path",
          width: "150",
          visible: true,
          align: "center",
        },
        {
          title: "类型",
          prop: "menuType",
          width: "100",
          visible: true,
          align: "center",
        },
        {
          title: "可见",
          prop: "visible",
          width: "100",
          visible: true,
          align: "center",
        },
        {
          title: "权限标识",
          prop: "perms",
          width: "150",
          visible: true,
          align: "center",
        },
      ],
      tableData: [],
      expandedAll: false, // 控制是否全部展开
      dialogMenuVisible: false,
      field: "",
      menuRow: {},
    };
  },
  computed: {
    isSuperAdmin() {
      return isSuperAdmin();
    },
  },
  mounted() {
    this.calculateTableHeight();
    this.initTable();
  },
  methods: {
    initTable() {
      let visibleValue = this.value == "2" ? "" : this.value;
      let data = {
        menuName: this.input,
        visible: visibleValue,
      };
      menuList(data).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    handleClick(row, filed) {
      switch (filed) {
        case "edit":
          this.dialogMenuVisible = true;
          this.field = "修改菜单";
          this.menuRow = row;
          break;
        case "add":
          this.dialogMenuVisible = true;
          this.field = "添加菜单";
          this.menuRow = row;
          break;
        case "delete":
          console.log(row);
          this.$confirm(`确认删除${row.menuName}菜单吗?`, "系统提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            menuDelete(row.menuId).then((res) => {
              if (res.code == 0) {
                this.$message.success(res.msg);
                this.initTable();
              } else {
                this.$message.error(res.msg);
              }
            });
          });
          break;
        default:
          break;
      }
    },

    // 处理表头显示隐藏
    handleCheckChange(checkedValues) {
      this.tableHeader.forEach((item) => {
        item.visible = checkedValues.includes(item.prop);
      });
      this.tableKey += 1;
    },
    handleSearchClick() {
      this.searchCardShow = !this.searchCardShow;
    },
    handleInitClick() {
      this.initTable();
    },
    // 展开/折叠所有节点
    toggleExpandAll() {
      this.expandedAll = !this.expandedAll;
      this.tableData.forEach((item) => {
        this.toggleExpanded(item, this.expandedAll);
      });
    },

    // 递归设置节点展开状态
    toggleExpanded(row, expanded) {
      // 设置当前行的展开状态
      this.$refs.multipleTable.toggleRowExpansion(row, expanded);

      // 递归处理子节点
      if (row.children && row.children.length > 0) {
        row.children.forEach((child) => {
          this.toggleExpanded(child, expanded);
        });
      }
    },
    resetForm() {
      this.value = "";
      this.initTable();
    },
    hasPermission(permission) {
      return hasPermission(permission);
    },
    calculateTableHeight() {
      // 根据容器实际高度计算表格高度
      this.$nextTick(() => {
        const container = this.$refs.multipleTable.$el?.parentElement;
        if (container) {
          // 减去表头和其他元素的高度
          this.tableHeight = container.clientHeight - 120; // 120为估计的其他元素高度
        }
      });
    },
  },
};
</script>
